package com.zhw.mybatis.executor;

import com.zhw.mybatis.config.ZhwConfiguration;
import com.zhw.mybatis.utils.JdbcUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SimpleExecutor implements ZhwExecutor {

    private ZhwConfiguration configuration = ZhwConfiguration.SingleZhwConfiguration.INSTENCE.getInstence();

    Connection conn = null;
    PreparedStatement ptmt = null;
    ResultSet rs = null;

    //使用TypeHandler 解决硬编码问题
    //操作数据库 连接数据库，获取数据
    public <T> T query(String sql, Object[] args,Class returnType) {
        conn = JdbcUtils.getConn(configuration.getDataSource().getUrl(), configuration.getDataSource().getUsername(), configuration.getDataSource().getPassword());
        try {

            ptmt = conn.prepareStatement(sql);
            for (int i = 1; i <= args.length; i++) {
                String typeName = args[i-1].getClass().getName();
                if(typeName.equals("java.lang.Integer")){
                    ptmt.setInt(i, (Integer) args[i-1]);
                }else if(typeName.equals("java.lang.String")){
                    ptmt.setString(i, (String) args[i-1]);
                }
            }
            rs = ptmt.executeQuery();
            while (rs.next()){
                try {
                    Object o = returnType.newInstance();
                    Field[] fields = o.getClass().getDeclaredFields();
                    for (int i = 0; i < fields.length; i++) {
                        Field field = fields[i];
                        Class<?> type = field.getType();
                        String name = field.getName();
                        if(type.getName().equals("java.lang.Integer")){
                            field.setAccessible(true);
                            int anInt = rs.getInt(name);
                            field.set(o,anInt);
                            field.setAccessible(false);
                        }else if(type.getName().equals("java.lang.String")){
                            field.setAccessible(true);
                            field.set(o,rs.getString(name));
                            field.setAccessible(false);
                        }else if(type.getName().equals("java.math.BigDecimal")){
                            field.setAccessible(true);
                            field.set(o,rs.getBigDecimal(name));
                            field.setAccessible(false);
                        }
                    }
                    return (T)o;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(rs,ptmt,conn);
        }
        return null;
    }




}
